package com.cictec.middleware.core;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.cictec.middleware.CloudConstants;
import com.cictec.middleware.core.entity.Bus;
import com.cictec.middleware.core.entity.Device;
import com.cictec.middleware.core.service.BusService;
import com.cictec.middleware.core.service.DeviceService;

@Component
public class InitDataService {

	private static Logger logger = LoggerFactory.getLogger(InitDataService.class);
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	@Autowired
	private BusService busService;
	@Autowired
	private DeviceService deviceService;


	public void initData() {
		Map<String, Bus> busMap = busService.selectMapBusByParams(null, "busUuid");
		Map<String, String> busBusUuidMap = new HashMap<String, String>();
		for (Bus bus : busMap.values()) {
			busBusUuidMap.put(bus.getBusUuid(), JSON.toJSONString(bus));
		}
		
		stringRedisTemplate.opsForHash().putAll(CloudConstants.REDIS_CLOUD_BUS, busBusUuidMap);
		
		List<Device> deviceList = deviceService.selectListDevice();
		Map<String, String> deviceDevCodeMap = new HashMap<String, String>();
		for (Device device : deviceList) {
			deviceDevCodeMap.put(device.getDevCode(), JSON.toJSONString(device));
		}
		stringRedisTemplate.opsForHash().putAll(CloudConstants.REDIS_CLOUD_DEVICE, deviceDevCodeMap);
		
		logger.debug("【InitDataService】加载车辆、设备信息到redis");
	}
	
	public void loadData(){
		new Thread() {
			public void run() {
				while(true){
					initData();
					try {
						Thread.sleep(300*1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}.start();
	}

}
